# PowerShell脚本：自动为所有Application类创建IDEA运行配置
# 设置输出编码为UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# 创建.idea/runConfigurations目录（如果不存在）
$runConfigsDir = ".idea/runConfigurations"
if (-not (Test-Path $runConfigsDir)) {
    New-Item -ItemType Directory -Path $runConfigsDir -Force
    Write-Host "创建目录: $runConfigsDir"
}

# 查找所有的Application类
$applicationFiles = Get-ChildItem -Path . -Recurse -Filter "*Application.java"

# 创建复合运行配置的内容
$compoundConfigContent = @"
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="Start All Services" type="CompoundRunConfigurationBase">

"@

# 为每个Application类创建单独的运行配置
foreach ($file in $applicationFiles) {
    # 提取类名和包名
    $content = Get-Content $file.FullName -Raw
    $className = $file.BaseName
    
    # 从文件内容中提取包名
    if ($content -match 'package\s+([\w\.]+);') {
        $packageName = $matches[1]
        
        # 从文件路径中提取模块名称
        $filePath = $file.FullName
        $modulePath = $filePath -replace "\\src\\main\\java\\.*$", ""
        $moduleName = $modulePath -replace ".*\\", ""
        
        Write-Host "处理: $className, 模块: $moduleName, 包: $packageName"
        
        # 创建运行配置文件名
        $configFileName = "$className.xml"
        $configPath = Join-Path $runConfigsDir $configFileName
        
        # 创建运行配置内容
        $configContent = @"
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="$className" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
    <module name="$moduleName" />
    <option name="SPRING_BOOT_MAIN_CLASS" value="$packageName.$className" />
    <method v="2">
      <option name="Make" enabled="true" />
    </method>
  </configuration>
</component>
"@
        
        # 写入配置文件
        Set-Content -Path $configPath -Value $configContent -Encoding UTF8
        Write-Host "创建运行配置: $configPath"
        
        # 添加到复合配置
        $compoundConfigContent += "    <toRun name=`"$className`" type=`"SpringBootApplicationConfigurationType`" />`n"
    }
    else {
        Write-Host "无法从 $($file.FullName) 提取包名，跳过此文件"
    }
}

# 完成复合配置
$compoundConfigContent += @"
    <method v="2" />
  </configuration>
</component>
"@

# 写入复合配置文件
$compoundConfigPath = Join-Path $runConfigsDir "Start_All_Services.xml"
Set-Content -Path $compoundConfigPath -Value $compoundConfigContent -Encoding UTF8
Write-Host "创建复合运行配置: $compoundConfigPath"

Write-Host "`n配置创建完成！请重启IDEA以加载新的运行配置。"
Write-Host "然后您可以在IDEA顶部工具栏的运行配置下拉菜单中选择'Start All Services'来启动所有服务。" 